import cv2
import mediapipe as mp
import time


class HandMoudle():
    def __init__(self,mode=False,maxHands=2,model_complexity=1,detectionCon=0.5,trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.model_complexity = model_complexity
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hand = self.mpHands.Hands()
        self.mpDraw = mp.solutions.drawing_utils


    def findHands(self,frame,draw=True):
        frameRGB = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
        self.results = self.hand.process(frameRGB)
        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(frame, handLms,
                                               self.mpHands.HAND_CONNECTIONS)
            return frame

    def findPosition(self,frame,handNo=0,draw=True):

        lmlist = []
        if self.results.multi_hand_landmarks:
            myhand = self.results.multi_hand_landmarks[handNo]
            # for handlm in self.results.multi_hand_landmarks:
            for id, lm in enumerate(myhand.landmark):
                h, w, c = frame.shape
                cx, xy = int(lm.x * w), int(lm.y * h)
                lmlist.append([id, cx, xy])
                if draw:
                    cv2.circle(frame, (cx, xy), 5, (255, 0, 255), cv2.FILLED)
        return lmlist

    def fpsVideo(self,frame):
        self.Ptime = 0
        Ctime = time.time()
        fps = 1 / (Ctime - self.Ptime)
        self.Ptime = Ctime
        cv2.putText(frame, 'FPS:' + str(int(fps)), (400, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 3)
if __name__=="__main__":
    cap = cv2.VideoCapture(0)
    cap.set(3, 640)
    cap.set(4, 480)
    detector = HandMoudle()
    while True:
        ret, frame = cap.read()
        frame = detector.findHands(frame)
        # lmlist = detector.findPosition(frame)
        # print(lmlist)

        cv2.imshow('frame', frame)
        cv2.waitKey(1)

